package com.cy.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义统一身份认证过滤器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    //Mono 是封装了0次或1次的一个请求异步调用链(Spring Framework 5 WebFlux)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        //实际项目中可以在此位置从redis中获取token信息(唯一标识)
        String token =
                exchange.getRequest().getQueryParams().getFirst("token");
        if (!"admin".equals(token)) {
            System.out.println("请先认证再访问");
            //设置响应状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置响应结束
            return exchange.getResponse().setComplete();
            //throw new RuntimeException("请先登录");
        }
        return chain.filter(exchange);//继续调用下一个过滤器
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
